package com.ls.controller.login;

import com.ls.base.BaseResult;
import com.ls.base.BaseResultUtil;
import com.ls.constant.SystemConstants;
import com.ls.controller.login.model.LoginModel;
import com.ls.controller.login.model.LoginOffLineModel;
import com.ls.exception.CommonExceptionEnums;
import com.ls.service.ILoginService;
import com.ls.utils.VerifyCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName LoginController
 * @Description 登录相关接口
 * @Author TangQuanBin
 * @Date 2019/9/14 10:19
 * @Version 1.0
 **/
@Api(value = "登录相关接口", description = "登录相关接口")
@Controller
@RequestMapping(value = "/login")
public class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    /**
     * 登录接口
     */
    @Autowired
    private ILoginService loginService;

    /**
     * RSA公钥
     */
    @Value("${RSA.publicKey}")
    private String publicKey;

    @ApiIgnore
    @ApiOperation(value = "获取公钥")
    @GetMapping(value = "/getPublicKey")
    @ResponseBody
    public BaseResult getPublicKey() {
        return BaseResultUtil.success(publicKey);
    }


    /**
     * 获取验证码图片和文本(验证码文本会保存在redis中)
     *
     * @param response
     * @return void
     */
    @ApiIgnore
    @ApiOperation(value = "获取验证码", notes = "获取验证码", httpMethod = "GET")
    @GetMapping(value = "/getVerifyCodeImage")
    @ResponseBody
    public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_LOWER, 4, null);
        session.removeAttribute(SystemConstants.VERIFYCODE);
        session.setAttribute(SystemConstants.VERIFYCODE, verifyCode);
        response.setContentType("image/jpeg");
        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
        ImageIO.write(bufferedImage, "jpeg", response.getOutputStream());
    }

    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
    @PostMapping(value = "login")
    @ResponseBody
    public BaseResult login(@Valid @RequestBody LoginModel loginModel) {
//        String sessionVerifyCode = (String) request.getSession().getAttribute(SystemConstants.VERIFYCODE);
        //8888方便直接调用接口测试
//        if (!SystemConstants.TEST_VERFICATION_CODE.equals(loginModel.getVerifyCode())) {
//            if (sessionVerifyCode == null || !sessionVerifyCode.equals(loginModel.getVerifyCode().toLowerCase())) {
//                return BaseResultUtil.error(CommonExceptionEnums.UNDEFINED_EXCEPTION.getCode(),
//                        "验证码错误或已过期,请刷新页面重试");
//            }
//            request.getSession().removeAttribute(SystemConstants.VERIFYCODE);
//        }
        return loginService.login(loginModel.getAccount(), loginModel.getPassword());
    }


    /**
     * 商家用户登录
     *
     * @param loginModel
     * @return
     */
    @ApiIgnore
    @PostMapping(value = "loginForOffLine")
    @ResponseBody
    public BaseResult loginForOffLine(@Valid @RequestBody LoginOffLineModel loginModel) {
        return loginService.login(loginModel.getAccount(), loginModel.getPassword());
    }


    @ApiOperation(value = "用户注销登录", notes = "用户注销登录", httpMethod = "GET")
    @GetMapping(value = "logout")
    @ResponseBody
    public BaseResult logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseResultUtil.success("注销成功");
    }


    /**
     * 拦截登录接口，返回json，由前端判断，跳转登录页面
     */
    @ApiIgnore
    @RequestMapping(value = "goLogin")
    @ResponseBody
    public BaseResult goLogin() {
        //清除session
        SecurityUtils.getSubject().logout();
        return BaseResultUtil.error(CommonExceptionEnums.LOGIN_OUT_OF_DATE.getCode(),
                CommonExceptionEnums.LOGIN_OUT_OF_DATE.getMessage());
    }

    /**
     * 没有权限时拦截到的接口
     */
    @ApiIgnore
    @GetMapping(value = "unauthorized")
    @ResponseBody
    public BaseResult unauthorized() {
        return BaseResultUtil.error(CommonExceptionEnums.NO_PERMISSION.getCode(),
                CommonExceptionEnums.NO_PERMISSION.getMessage());
    }

}
